<?php
    $masterView = MasterView::getInstance();
    $topSocialPlatformsData = $masterView->metricsView->topSocialPlatformsData;
?>
<div class="header" id="header" streamid="<?php echo $this->streamView->model->streamId; ?>" messageid="">
    <div class="top-banner">
        <p>
            <span class="menu" id="menu-button">
                <i class="fa fa-bars fa-2x"></i>
            </span>
            <span class="title"><?php echo $this->streamView->model->name; ?></span>
            <span class="detail" id="filter-button"><i class="fa fa-bookmark fa-2x"></i></span>
        </p>
    </div>
    <div class="option option-compare" id="option">
        <div class="filter">
            <a href="/#stream/"><i class="ub ub-mention ub-2x"></i></a>
                COMPARISION
            <a href="/#metrics/"><i class="ub ub-metrics ub-2x"></i></a>
        </div>
        <div class="stream-select" id="stream-select-div">
            <span class="stream-select" id="stream-select"><?php $streams = Stream::getStreams($this->streamView->model->folderId); echo $streams[0]->name; ?></span>
            <span class="caret"><i class="fa fa-caret-down"></i></span>
        </div>
        <ul class="choose-item-compare hide" id="stream-list">
            <?php
            $first = true;
            foreach ($streams as $stream) {
                if($stream->streamId != $this->streamView->model->streamId){
                    if($first){
                        $first = false;
                        echo '<li class="selected" value="' . base64_encode($stream->streamId) . '"><span>' . $stream->name . '</span><i class="fa fa-check"></i></li><span class="separator"></span>';
                    } else{
                        echo '<li class="" value="' . base64_encode($stream->streamId) . '"><span>' . $stream->name . '</span><i class="fa fa-check"></i></li><span class="separator"></span>';
                    }
                }
            }
            ?>
        </ul>
    </div>
</div>
<div class="content" id="content">
    <div class="content content-thread content-comparision">
        <div class="wrap-block source-block">
            <?php include "SOVHTML.php"; ?>
        </div>
        <div class="wrap-block source-block">
            <?php include "TrendlineHTML.php"; ?>
        </div>	
    </div>
</div>
<script>
    var sov, trend;
    var SOVReq, TrendReq;
    var SOVMetrics = document.getElementById('metrics-sov');
    var TrendMetrics = document.getElementById('metrics-trend');
    var streamname_metrics = [document.getElementById('stream-select').textContent];
    var stream_metrics = [document.getElementById('stream-list').getElementsByClassName('selected')[0].attributes['value'].value];
    var stream_metrics_old = document.getElementById('stream-list').getElementsByClassName('selected')[0].attributes['value'].value;
   
    var loadSOV_complete = function(data) {
        $('#sov1').removeClass('hide');
        $('#sov2').removeClass('hide');
        if (data !== undefined){
            if (data.trim() === '"Your query has no result! Try again!"') {
                SOVMetrics.getElementsByClassName('notice')[0].textContent = 'NOT ENOUGH DATA TO SHOW. PLEASE TRY AGAIN LATER.';
                removeClass(SOVMetrics.getElementsByClassName('notice')[0], 'hide');
                addClass(SOVMetrics.getElementsByClassName('sov-loading')[0], 'hide');
                return;
            }
            sov = JSON.parse(data);
            addClass(SOVMetrics.getElementsByClassName('notice')[0], 'hide');
            addClass(SOVMetrics.getElementsByClassName('sov-loading')[0], 'hide');
        }
        var categories = new Array();
        var series = new Array();
        var typeOfChart = $('#metrics-sov .hourly-filter-wrapper .selected').text();
        switch (typeOfChart) {
            case "Total":
                var curStreamName = document.getElementById('header').getElementsByClassName('title')[0].textContent;
                for (i = 0; i < sov.total.data.length; i++) {
                    if (sov.total.name[i] !== curStreamName)
                        series[i] = {name: sov.total.name[i], y: sov.total.data[i]};
                    else
                        series[i] = {name: sov.total.name[i], y: sov.total.data[i], sliced: true, selected: true};
                }
                categories = sov.total.name;
                $(function() {
                    if ($('#sov2').length === 0)
                        return;
                    $('#sov2').highcharts({
                        chart: {
                            plotBackgroundColor: null,
                            plotBorderWidth: null,
                            plotShadow: false
                        },
                        title: {
                            text: null
                        },
                        tooltip: {
                            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                        },
                        plotOptions: {
                            pie: {
                                allowPointSelect: true,
                                cursor: 'pointer',
                                dataLabels: {
                                    enabled: true,
                                    color: '#000000',
                                    connectorColor: '#000000',
                                    format: '<b>{point.name}</b>: {point.percentage:.1f} %'
                                }
                            }
                        },
                        legend: {
                            borderWidth: 0,
                        },
                        series: [{
                                type: 'pie',
                                name: 'Number of mention',
                                data: series,
                                events: {click: function(e) {
                                        var streamName = e.point.name.trim();
                                        $('.stream-select option').each(function() {
                                            if ($(this).text().trim() === streamName) {
                                                window.location.href = '/#stream/' + $(this).attr('value');
                                            }
                                        });
                                    }}
                            }]
                    });
                });
                categories = [''];
                for (i = 0; i < sov.total.data.length; i++) {
                    series[i] = {name: sov.total.name[i], data: [sov.total.data[i]]};
                }
                break;
            case "Monthly":
                categories = sov[0].monthly.name;
                for (var i = 0; i < count(sov) - 1; i++) {
                    series[i] = {name: sov[i].stream.name, data: sov[i].monthly.data};
                }
                break;
            case "Daily":
                categories = sov[0].daily.date;
                for (var i = 0; i < count(sov) - 1; i++) {
                    series[i] = {name: sov[i].stream.name, data: sov[i].daily.data};
                }
                break;
        }
        $(function() {
            if ($('#sov1').length === 0)
                return;
            $('#sov1').highcharts({
                chart: {
                    type: 'column'
                },
                title: {
                    text: ''
                },
                xAxis: {
                    categories: categories,
                },
                yAxis: {
                    min: 0,
                    minTickInterval: 1,
                    gridLineWidth: 0,
                    title: {
                        text: null,
                        align: 'high'
                    },
                    labels: {
                        overflow: 'justify',
                        enabled: false
                    }
                },
                tooltip: {
                    formatter: function() {
                        return '<b>' + this.series.name + '</b><br/>' +
                                this.x + ': ' + this.y;
                    }
                },
                plotOptions: {
                    column: {
                        dataLabels: {
                            enabled: true
                        }
                    }
                },
                legend: {
                    borderWidth: 0,
                },
                credits: {
                    enabled: false
                },
                series: series
            });
        });
    };

    var loadTrend_complete = function(data){
        $('#trendline').removeClass('hide');
        if (data !== undefined){
            if (data.trim() === '"Your query has no result! Try again!"') {
                TrendMetrics.getElementsByClassName('notice')[0].textContent = 'NOT ENOUGH DATA TO SHOW. PLEASE TRY AGAIN LATER.';
                removeClass(TrendMetrics.getElementsByClassName('notice')[0], 'hide');
                addClass(TrendMetrics.getElementsByClassName('trend-loading')[0], 'hide');
                return;
            }
            trend = JSON.parse(data);
            addClass(TrendMetrics.getElementsByClassName('notice')[0], 'hide');
            addClass(TrendMetrics.getElementsByClassName('trend-loading')[0], 'hide');
        }
        var categories = new Array();
        var series = new Array();
        var typeOfChart = $('#metrics-trend .hourly-filter-wrapper .selected').text();
        switch (typeOfChart) {
            case "Daily":
                $('#metrics-trend .notice').addClass('hide');
                categories = trend[0].daily.date;
                for (i = 0; i < count(trend); i++) {
                    series[i] = {name: trend[i].stream.name, data: trend[i].daily.data};
                }
                $(function() {
                    if ($('#trendline').length === 0)
                        return;
                    $('#trendline').highcharts({
                        chart: {
                            type: 'areaspline',
                            spacingBottom: 0
                        },
                        title: {
                            text: '',
                            x: -20 //center
                        },
                        xAxis: {
                            categories: categories
                        },
                        yAxis: {
                            title: {
                                text: ''
                            },
                            plotLines: [{
                                    value: 0,
                                    width: 1,
                                    color: '#808080',
                                }],
                            gridLineWidth: 0,
                            labels: {
                                formatter: function() {
                                    return this.value / 1000 + 'k';
                                }
                            },
                        },
                        tooltip: {
                            formatter: function() {
                                return '<b>' + this.series.name + '</b><br/>' +
                                        this.x + ': ' + this.y;
                            }
                        },
                        legend: {
                            borderWidth: 0,
                        },
                        plotOptions: {
                            series: {
                                marker: {
                                    fillColor: 'transparent',
                                    lineWidth: 0,
                                    fillOpacity: 0.1,
                                    lineColor: 'transparent', // inherit from series
                                    states: {
                                        hover: {
                                            lineWidth: 1,
                                            radius: 4,
                                            lineColor: '#EEE',
                                            fillColor: '#FFF'
                                        }
                                    }
                                },
                                fillOpacity: 0.2,
                            }},
                        series: series
                    });
                });
                break;
            case "Monthly":
                if (trend[0].monthly.name.length === 1) {
                    $('#trendline').addClass('hide');
                    $('#metrics-trend .notice').html('NOT ENOUGH DATA TO SHOW. PLEASE TRY AGAIN LATER.');
                    $('#metrics-trend .notice').removeClass('hide');
                    break;
                }
                categories = trend[0].monthly.name;
                for (i = 0; i < count(trend); i++) {
                    series[i] = {name: trend[i].stream.name, data: trend[i].monthly.data};
                }
                $(function() {
                    if ($('#trendline').length === 0)
                        return;
                    $('#trendline').highcharts({
                        chart: {
                            type: 'areaspline',
                            spacingBottom: 0
                        },
                        title: {
                            text: '',
                            x: -20 //center
                        },
                        xAxis: {
                            categories: categories
                        },
                        yAxis: {
                            title: {
                                text: ''
                            },
                            plotLines: [{
                                    value: 0,
                                    width: 1,
                                    color: '#808080',
                                }],
                            gridLineWidth: 0,
                            labels: {
                                formatter: function() {
                                    return this.value / 1000 + 'k';
                                }
                            },
                        },
                        tooltip: {
                            formatter: function() {
                                return '<b>' + this.series.name + '</b><br/>' +
                                        this.x + ': ' + this.y;
                            }
                        },
                        legend: {
                            layout: 'vertical',
                            align: 'right',
                            verticalAlign: 'middle',
                            borderWidth: 0,
                        },
                        plotOptions: {
                            series: {
                                marker: {
                                    fillColor: 'transparent',
                                    lineWidth: 0,
                                    fillOpacity: 0.1,
                                    lineColor: 'transparent', // inherit from series
                                    states: {
                                        hover: {
                                            lineWidth: 1,
                                            radius: 4,
                                            lineColor: '#EEE',
                                            fillColor: '#FFF'
                                        }
                                    }
                                },
                                fillOpacity: 0.2,
                            }},
                        series: series
                    });
                });
                break;
        }
        $('#metrics-trend .highcharts-container').height($('.highcharts-container').height() + 10);
        $('#metrics-trend .highcharts-container svg').height($('.highcharts-container svg').height() + 10);
    };
    
    function addEventCompareView(){
        //add event click stream-select
        document.getElementById('stream-select-div').addEventListener('click', function(){
            if(window.hasClass(document.getElementById('stream-list'), 'hide')){
                removeClass(document.getElementById('stream-list'), 'hide');
            } else {
                addClass(document.getElementById('stream-list'), 'hide');
                if(stream_metrics_old !== stream_metrics.join(', ')){
                    stream_metrics_old = stream_metrics.join(', ');
                    loadComparison();
                }
            }
        }, false);
        //add event choose stream
        var stream_select = document.getElementById('stream-list').getElementsByTagName('li');
        for(var i = 0; i < stream_select.length; i++){
            stream_select[i].addEventListener('click', function(){
                if(window.hasClass(this, 'selected')){
                    removeClass(this, 'selected');
                    var index = streamname_metrics.indexOf(this.getElementsByTagName('span')[0].textContent);
                    streamname_metrics.splice(index, 1);
                    stream_metrics.splice(index, 1);
                } else {
                    addClass(this, 'selected');
                    streamname_metrics.push(this.getElementsByTagName('span')[0].textContent);
                    stream_metrics.push(this.attributes['value'].value);
                }
                document.getElementById('stream-select').textContent = streamname_metrics.join(', ');
            }, false);
        }
        //the first loadChart
        loadComparison();
    }
    
    function loadComparison() {
        dateFrom = document.getElementById('datefrom-filter').attributes['value'].value;
        dateTo = document.getElementById('dateto-filter').attributes['value'].value;
        SOVRequest(streamId, stream_metrics.join(','), dateFrom, dateTo, language, type, tag, sentiment);
        TrendRequest(streamId, stream_metrics.join(','), dateFrom, dateTo, language, type, tag, sentiment);
        reloadChartEffect();
    }
    
    function SOVRequest(streamId, streamIds, dateFrom, dateTo, language, type, tag, sentiment){
        if (SOVReq !== undefined){
            SOVReq.abort();
        }
        var url = "/ws/comparesov/" + streamId + "/" + streamIds + "/" + "0" + "/" + dateFrom + "/" + dateTo + "/" + language + "/" + type + "/" + tag + "/" + sentiment;
        if(state !== 4)
            removeClass(document.getElementsByClassName("loading")[0], 'hide');
        SOVReq = sendRequest(url, loadSOV_complete, process);
    }
    
    function TrendRequest(streamId, streamIds, dateFrom, dateTo, language, type, tag, sentiment){
        if(TrendReq !== undefined)
            TrendReq.abort();
        var url = "/ws/comparetrend/" + streamId + "/" + streamIds + "/" + "/" + dateFrom + "/" + dateTo + "/" + language + "/" + type + "/" + tag + "/" + sentiment;
        if(state !== 4)
            removeClass(document.getElementsByClassName("loading")[0], 'hide');
        TrendReq = sendRequest(url, loadTrend_complete, process);
    }

    function reloadChartEffect(){
        if(stream_metrics.length === 0){
            if (SOVReq !== undefined){
                SOVReq.abort();
            }
            if(TrendReq !== undefined){
                TrendReq.abort();
            }
            $('#trendline').addClass('hide');
            $('#sov1').addClass('hide');
            $('#sov2').addClass('hide');
            $('#metrics-sov .notice').html('PLEASE SELECT AT LEAST 1 STREAM TO COMPARE.');
            $('#metrics-trend .notice').html('PLEASE SELECT AT LEAST 1 STREAM TO COMPARE.');
            removeClass(SOVMetrics.getElementsByClassName('notice')[0], 'hide');
            removeClass(TrendMetrics.getElementsByClassName('notice')[0], 'hide');
            addClass(SOVMetrics.getElementsByClassName('sov-loading')[0], 'hide');
            addClass(TrendMetrics.getElementsByClassName('trend-loading')[0], 'hide');
        }else {
            removeClass(SOVMetrics.getElementsByClassName('sov-loading')[0], 'hide');
            removeClass(TrendMetrics.getElementsByClassName('trend-loading')[0], 'hide');
            addClass(SOVMetrics.getElementsByClassName('notice')[0], 'hide');
            addClass(TrendMetrics.getElementsByClassName('notice')[0], 'hide');
            document.getElementById('sov1').innerHTML = '';
            document.getElementById('sov2').innerHTML = '';
            document.getElementById('trendline').innerHTML = '';
        }
    }
    
    function count(object) {
        var key, count = 0;
        for (key in object) {
            if (object.hasOwnProperty(key)) {
                count++;
            }
        }
        return count;
    }
    
    //hourly wrapper of metrics sov
    $(document).on('click', '#metrics-sov .hourly-filter-wrapper li', function(){
        $('#metrics-sov .hourly-filter-wrapper .selected').removeClass('selected');
        $(this).addClass('selected');
        if(streamname_metrics.length > 0){
            loadSOV_complete();
        }
    });
    //hourly wrapper of metrics trendline
    $(document).on('click', '#metrics-trend .hourly-filter-wrapper li', function(){
        $('#metrics-trend .hourly-filter-wrapper .selected').removeClass('selected');
        $(this).addClass('selected');
        if(streamname_metrics.length > 0){
            loadTrend_complete();
        }
    });
                        
    addEventCompareView();
</script>